package com.opesoft.pf.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.beanutils.BeanUtils;

import com.opesoft.fw.ajax.Ajax;
import com.opesoft.pf.page.ListCtrl;
import com.opesoft.pf.page.QueryResultData;

public class ListCtrlAction
{
	@Ajax(clientCall=true)
	static public QueryResultData serverQuery(String countQL,String queryQL,String[] properties,int nowPage,int pageSize)
	{
		ListCtrl lc=new ListCtrl();
		String[][] data=new String[0][];

		EntityManager em=SessionManager.open();
		try
		{
			Object obj=em.createQuery(countQL).getSingleResult();
			lc.setAllRecord(Integer.valueOf(obj+""));
			
			lc.setPageSize(pageSize);
			lc.setNowPage(nowPage);

			Query q=em.createQuery(queryQL);
			q.setFirstResult(lc.getPageSize()*(lc.getNowPage()-1));
			q.setMaxResults(lc.getPageSize());

			List list=q.getResultList();

			if(list!=null&&properties!=null)
			{
				data=new String[list.size()][properties.length];

				for(int i=0;i<list.size();i++)
				{
					obj=list.get(i);

					for(int j=0;j<properties.length;j++)
					{
						data[i][j]=BeanUtils.getProperty(obj,properties[j]);
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			SessionManager.rollback();
		}

		QueryResultData result=new QueryResultData();
		result.setData(data);
		result.setListCtrl(lc.toMap());

		return result;
	}
}
